package cn.edu.scau.cmi.linpeiwei.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.text.Text;

import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.AnchorPane;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;

import org.springframework.context.ApplicationContext;

import cn.edu.scau.cmi.linpeiwei.comprehension.dao.StudentDao;
import cn.edu.scau.cmi.linpeiwei.comprehension.dao.TeacherDao;
import cn.edu.scau.cmi.linpeiwei.comprehension.domain.Student;
import cn.edu.scau.cmi.linpeiwei.comprehension.domain.Teacher;
import cn.edu.scau.cmi.linpeiwei.comprehension.util.ComprehensionApplicationContextUtil;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;

public class ComprehensionController extends AnchorPane implements Initializable{
	@FXML
	private Button addS;
	@FXML
	private Button delS;
	@FXML
	private Button delT;
	@FXML
	private TextField sid;
	@FXML
	private TextField sname;
	@FXML
	private TextField semail;
	@FXML
	private Button addT;
	@FXML
	private TextField tid;
	@FXML
	private TextField tname;
	@FXML
	private Text info;
	@FXML
	private Text sidInfo;
	@FXML
	private Text tidInfo;
	@FXML
	private ListView<CheckBox> lv;
	@FXML
	private ListView<RadioButton> lv1;
	
	
	private ApplicationContext applicationContext;
	private StudentDao studentDao;
	private TeacherDao teacherDao;
	private ObservableList<CheckBox> stdList;
	private ObservableList<RadioButton> tchList;
	private List setS;
	private List setT;
	private Set<Student> selectSS;
	private Teacher tmpTeacher;
	private ToggleGroup tg;

	// Event Listener on Button[#addS].onAction
	@FXML
	public void addStudent(ActionEvent event) {
		// TODO Autogenerated
		//System.out.println(studentDao.findById((long) 111));
		//System.out.println(((Student)studentDao.findAll().get(0)).getName());
		if(!sname.getText().isEmpty()) {
			Student student = new Student();
			if(!sid.getText().isEmpty()) {
				student.setId(Long.parseLong(sid.getText()));
			}
			if(!semail.getText().isEmpty()) {
				student.setEmail(semail.getText());
			}
			
			if(tmpTeacher != null) {
				student.setTeacher(tmpTeacher);
			}
			if(!sname.getText().isEmpty()) {
				student.setName(sname.getText());
			}
			if(studentDao.findById(Long.parseLong(sid.getText())) == null) {
				if(studentDao.save(student)) {
					info.setText("添加成功");
					
				}else {
					info.setText("添加失败");
				}
			}else {
				if(studentDao.update(student)) {
					info.setText("更新成功");
					
				}else {
					info.setText("更新失败");
				}
			}
			flash();
			
		}else {
			info.setText("用户名不能为空");
		}
		
		
	}
	// Event Listener on Button[#addT].onAction
	@FXML
	public void addTeacher(ActionEvent event) {
//		System.out.println(teacherDao.findById((long)15).getName());
		if(!tname.getText().isEmpty()) {
			Teacher teacher = new Teacher();
			if(!tid.getText().isEmpty()) {
				teacher.setId(Long.parseLong(tid.getText()));
			}
			if(!tname.getText().isEmpty()) {
				teacher.setName(tname.getText());
			}
			
			if(teacherDao.findById(Long.parseLong(tid.getText())) == null) {
				System.out.println("添加");
				if(teacherDao.save(teacher)) {
					info.setText("添加成功");
					for(Student tmp:selectSS) {
						tmp.setTeacher(teacherDao.findById(Long.parseLong(tid.getText())));
						studentDao.update(tmp);
					}
					flash();
				}else {
					info.setText("添加失败");
				}
			}else {
				System.out.println("更新");
				if(teacherDao.update(teacher)) {
					info.setText("更新成功");
					for(Student tmp:selectSS) {
						tmp.setTeacher(teacherDao.findById(Long.parseLong(tid.getText())));
						studentDao.update(tmp);
					}
					flash();
				}else {
					info.setText("更新失败");
				}
			}
			if(teacherDao.save(teacher)) {
				info.setText("添加成功");
				for(Student tmp:selectSS) {
					tmp.setTeacher(teacherDao.findById(Long.parseLong(tid.getText())));
					studentDao.update(tmp);
				}
				flash();
			}else {
				info.setText("添加失败");
			}
			
		}else {
			info.setText("用户名不能为空");
		}
	}
	// Event Listener on Button[#delT].onAction
	@FXML
	public void delTeacher(ActionEvent event) {
		teacherDao.delete(tmpTeacher);
		flash();
	}
	
	// Event Listener on Button[#delS].onAction
	@FXML
	public void delStudent(ActionEvent event) {
		for(Student tmp:selectSS) {
			studentDao.delete(tmp);
		}
		flash();
	}
	
	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		// TODO 自动生成的方法存根
		applicationContext = ComprehensionApplicationContextUtil.getApplicationContext();
		studentDao=(StudentDao) applicationContext.getBean("StudentDao");
		teacherDao=(TeacherDao) applicationContext.getBean("TeacherDao");
		tchList = FXCollections.observableArrayList();
		stdList = FXCollections.observableArrayList();
		setS = new ArrayList<>();
		setT = new ArrayList<>();
		selectSS = new HashSet<Student>();
		tg = new ToggleGroup();
		flash();
	}
	
	private void flash() {
		tchList.clear();
		stdList.clear();
		setS = studentDao.findAll();
		setT = teacherDao.findAll();
		if(lv1!=null) {
			lv1.getItems().clear();	
		}
		if(lv!=null) {
			lv.getItems().clear();
		}
		
		for(Object tmp : setT) {
//			tchList.add(((Teacher)tmp).getId() + " - " + ((Teacher) tmp).getName());
			RadioButton rb = new RadioButton(((Teacher)tmp).getId() + " - " + ((Teacher) tmp).getName());
			rb.setToggleGroup(tg);
			tchList.add(rb);
			rb.selectedProperty().addListener(new ChangeListener<Boolean>() {
		        public void changed(ObservableValue<? extends Boolean> ov,
		            Boolean old_val, Boolean new_val) {
		                tmpTeacher = (Teacher)tmp;
		        }
		    });
			
		}
		
		lv1.getItems().addAll(tchList);
		
		
		
		for(Object tmp : setS) {
			String tString = " ";
			if(((Student) tmp).getTeacher()!=null)
				tString = ((Student) tmp).getTeacher().getId() + " - " + ((Student) tmp).getTeacher().getName(); 
			CheckBox cb = new CheckBox(((Student) tmp).getId() + " - " + ((Student) tmp).getName()  + "(" + tString + ")");
			stdList.add(cb);
			cb.selectedProperty().addListener(new ChangeListener<Boolean>() {
		        public void changed(ObservableValue<? extends Boolean> ov,
		            Boolean old_val, Boolean new_val) {
		                selectSS.add((Student) tmp);
		        }
		    });
		}
		lv.getItems().addAll(stdList);
	}
}
